<template>
  <div>
    <a-card :bordered="false" :bodyStyle="tstyle">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="16" :sm="24">
            <span class="base-title">{{baseInfo.userInfo.name}} 同学，
              <template v-if="baseInfo.stuTagDesc">
                您是{{baseInfo.stuTagDesc}}学生，
              </template>
              已为您列出当前开放选课的课程
            </span>
            </a-col>
            <a-col :md="8" :sm="24">
              选课校验：
              <a-tag color='red' v-if="checkResult===0">
                不合格
              </a-tag>
              <a-tag color='red' v-if="checkResult===0 && checkReason">
                {{checkReason}}
              </a-tag>
              <a-tag color='green' v-if="checkResult===1">
                合格
              </a-tag>
            </a-col>
            <a-col :md="16" :sm="24">
              <span class="base-title">{{baseInfo.schoolYear?baseInfo.schoolYear.name:'无'}}</span>
              {{baseInfo.schoolTerm?baseInfo.schoolTerm.name:'无'}}
            </a-col>
            <a-col :md="8" :sm="24">
              选课时间:
              {{selectionStartDate}} ~ {{selectionEndDate}}
            </a-col>
            <a-col :md="16" :sm="24">
              <a-form-item label="请选择当前开放的实验课程">
                <a-select v-model="queryParam.coursePublishId" allow-clear placeholder="请选择实验课程" @change="changeCourse">
                  <a-select-option v-for="(item,index) in baseInfo.coursePublishList" :key="index" :value="item.id">{{
                    item.courseName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-button type="primary" @click="checkCourseSelection" :disabled="!queryParam.coursePublishId">校验选课
              </a-button>
              <a-popconfirm
                title="确定要清空选课吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="emptyCourseSelection"
              >
                <a-button style="margin-left: 8px" type="danger" :disabled="!queryParam.coursePublishId">清空选课</a-button>
              </a-popconfirm>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false">
      <a-table
        bordered
        ref="table"
        :columns="columns"
        :dataSource="loadData"
        :loading="tableLoading"
        :pagination="false"
        :rowKey="(record) => record.id"
      >
        <span slot="frequencyDay" slot-scope="text, record">
          <a-tag color="orange">{{'星期'+text}}</a-tag>
        </span>

        <span v-for="(item,index) in cryData.coursePublishFrequencyList"
              :slot="['frequencyIndex-',item.frequencyIndex].join('')" slot-scope="text, record">
          <template v-if="text">
            <a-tag color='red' v-if="text.fullFlag">
              已选{{text.courseSelectionNum}}人
            </a-tag>
            <a-tag color='green' v-if="!text.fullFlag">
              已选{{text.courseSelectionNum}}人
            </a-tag>
            <a-popconfirm
              title="确定选择本次实验课程选课吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="toCourseSelection(record,text)"
            >
              <a-button type="primary" size="small" v-if="!text.courseSelectionId && text.optFlag && !text.fullFlag">
                确定
              </a-button>
            </a-popconfirm>
            <a-popconfirm
              title="确定取消本次实验课程选课吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="cancelCourseSelection(text.courseSelectionId)"
            >
              <a-button type="danger" size="small" v-if="text.courseSelectionId" @click="">
                取消
              </a-button>
            </a-popconfirm>
          </template>
        </span>
      </a-table>
    </a-card>
  </div>
</template>

<script>

  import {
    cancelCourseSelection,
    checkCourseSelection,
    emptyCourseSelection,
    getCourseSelectionBaseInfo,
    getCourseSelectionCryInfo,
    toCourseSelection
  } from '@/api/modular/system/courseSelectionManage'

  const renderContent = (value) => {
    const obj = {
      children: value,
      attrs: {}
    }
    return obj
  }

  export default {
    components: {},
    data() {
      return {
        tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
        queryParam: {
          coursePublishId: ''
        },
        baseInfo: '',
        cryColumns: [
          {
            title: '实验模块',
            dataIndex: 'moduleName',
            customRender(_, row) {
              return {
                children: row.moduleName,
                attrs: {
                  rowSpan: row.rowSpan
                }
              }
            }
          },
          {
            title: '模块选课要求',
            dataIndex: 'moduleDesc',
            customRender(_, row) {
              return {
                children: row.moduleDesc,
                attrs: {
                  rowSpan: row.rowSpan
                }
              }
            }
          },
          {
            title: '实验项目',
            dataIndex: 'projectName',
            customRender(_, row) {
              return {
                children: row.projectName,
                attrs: {
                  rowSpan: row.rowSpan
                }
              }
            }
          },
          {
            title: '实验教室',
            dataIndex: 'classroomName'
          },
          {
            title: '任课老师',
            dataIndex: 'teacherName'
          },
          {
            title: '开课日期',
            dataIndex: 'frequencyDay',
            scopedSlots: { customRender: 'frequencyDay' }
          },
          {
            title: '限选人数',
            dataIndex: 'maxStudents'
          }
        ],
        // 表头
        columns: [],
        loadData: '',
        tableLoading: false,
        cryData: '',
        checkResult: '',
        checkReason: '',
        selectionStartDate: '',
        selectionEndDate: ''
      }
    },
    created() {

    },
    mounted() {
      this.initColumns()
      this.getBaseInfo()
    },
    methods: {
      // 合并单元格，这里我抽出了一个函数，调用的时候只需要将dataIndex作为参数传入即可
      rowSpan(key) {
        let arr = this.loadData
          .reduce((result, item) => {
            if (result.indexOf(item[key]) < 0) {
              result.push(item[key])
            }
            return result
          }, [])
          .reduce((result, keys) => {
            const children = this.loadData.filter((item) => item[key] === keys)
            result = result.concat(
              children.map((item, index) => ({
                ...item,
                [`${key}RowSpan`]: index === 0 ? children.length : 0
              }))
            )
            return result
          }, [])
        this.loadData = arr
      },
      initColumns() {
        let tempColumns = []
        this.cryColumns.map((item) => {
          tempColumns.push(item)
        })
        this.columns = tempColumns
      },
      getBaseInfo() {
        getCourseSelectionBaseInfo({
          publishState: 1
        }).then((res) => {
          if (res.success) {
            this.baseInfo = res.data
            if (res.data.coursePublishList.length > 0) {
              this.queryParam.coursePublishId = res.data.coursePublishList[0].id
              this.changeCourse(res.data.coursePublishList[0].id)
              this.selectionStartDate = res.data.coursePublishList[0].selectionStartDate
              this.selectionEndDate = res.data.coursePublishList[0].selectionEndDate
            }
          } else {
            this.$message.error('获取选课基础信息异常：' + res.message)
          }
        })
      },
      changeCourse(value) {
        if (value) {
          let coursePublishData = this.baseInfo.coursePublishList.filter(item => item.id === value)
          this.selectionStartDate = coursePublishData[0].selectionStartDate
          this.selectionEndDate = coursePublishData[0].selectionEndDate
        } else {
          this.selectionStartDate = ''
          this.selectionEndDate = ''
        }
        this.tableLoading = true
        getCourseSelectionCryInfo({
          coursePublishId: value
        }).then((res) => {
          if (res.success) {
            this.initColumns()
            this.cryData = res.data
            this.appendColumns(res.data.coursePublishFrequencyList)
            this.loadData = res.data.courseScheduleVoList
            // this.rowSpan('moduleName')
            // this.rowSpan('moduleDesc')
          } else {
            this.$message.error('获取选课内容信息异常：' + res.message)
          }
        }).finally(() => {
          this.tableLoading = false
        })
      },
      appendColumns(list) {
        list?.map((item) => {
          this.columns.push({
            title: '第' + item.frequencyIndex + '轮（' + item.weekStart + '-' + item.weekEnd + '周）',
            dataIndex: 'frequencyIndex-' + item.frequencyIndex,
            scopedSlots: { customRender: 'frequencyIndex-' + item.frequencyIndex }
          })
        })
      },
      toCourseSelection(record, coursePublishFrequencyItem) {
        toCourseSelection({
          coursePublishId: coursePublishFrequencyItem.coursePublishId,
          courseScheduleId: coursePublishFrequencyItem.courseScheduleId,
          courseScheduleFrequencyId: coursePublishFrequencyItem.courseScheduleFrequencyId,
          frequencyIndex: coursePublishFrequencyItem.frequencyIndex,
          frequencyDay: record.frequencyDay
        }).then((res) => {
          if (res.success) {
            this.changeCourse(this.queryParam.coursePublishId)
            this.$message.success('添加实验选课成功')
            this.checkCourseSelection()
          } else {
            this.$message.error('添加实验选课失败：' + res.message)
          }
        })
      },
      cancelCourseSelection(courseSelectionId) {
        cancelCourseSelection({
          id: courseSelectionId
        }).then((res) => {
          if (res.success) {
            this.changeCourse(this.queryParam.coursePublishId)
            this.$message.success('取消实验选课成功')
            this.checkCourseSelection()
          } else {
            this.$message.error('取消实验选课失败：' + res.message)
          }
        })
      },
      checkCourseSelection() {
        if (this.queryParam.coursePublishId) {
          checkCourseSelection({
            coursePublishId: this.queryParam.coursePublishId
          }).then((res) => {
            if (res.success) {
              this.checkResult = res.data.checkResult
              if (res.data.checkResult === 0) {
                this.checkReason = '至少选择' + res.data.targetNum + '个实验项目'
              } else {
                this.checkReason = ''
              }
            } else {
              this.$message.error('选课校验失败：' + res.message)
            }
          })
        } else {
          this.$message.error('请先选择一个实验课程！')
        }
      },
      emptyCourseSelection() {
        if (this.queryParam.coursePublishId) {
          emptyCourseSelection({
            coursePublishId: this.queryParam.coursePublishId
          }).then((res) => {
            if (res.success) {
              this.changeCourse(this.queryParam.coursePublishId)
              this.$message.success('清空实验选课成功')
              this.checkCourseSelection()
            } else {
              this.$message.error('清空实验选课失败：' + res.message)
            }
          })
        } else {
          this.$message.error('请先选择一个实验课程！')
        }
      }
    }
  }
</script>
<style lang="less">
  .base-title {
    font-weight: bold;
    color: #015478;
  }
</style>